/**
 * @Author: wangliuyang
 * @Date: 2021/9/7 15:23
 * @Description:
 */
public class Solution_79 {
    public boolean exist(char[][] board, String word) {
        boolean ans = false;
        char[] chars = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                ans = ans || exist(board, i, j, chars, 0);
                if (ans) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean exist(char[][] board, int i, int j, char[] words, int index) {
        if (index == words.length) {
            return true;
        }
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
            return false;
        }
        if (board[i][j] != words[index]) {
            return false;
        }
        char temp = board[i][j];
        board[i][j] = 0;
        //标记当前位置已经来过,后续过程不要来,后面会回溯
        boolean ans = exist(board, i + 1, j, words, index + 1)
                || exist(board, i - 1, j, words, index + 1)
                || exist(board, i, j + 1, words, index + 1)
                || exist(board, i, j -1, words, index + 1);
        board[i][j] = temp;
        return ans;
    }
}
